
package labb6;

import java.io.*;
import java.net.URL;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;


public class linkTable {
    static InputStream in;
    static HTMLDocument doc;
    static HTMLEditorKit kit;
    static String[][] linkArray;
    static InputStreamReader reader;
   
   public void linkTable(){
       
   }
    
   public String[][] getLinks(String adress){
        linkArray = new String[50][2];
        kit = new HTMLEditorKit();
        doc = (HTMLDocument)kit.createDefaultDocument();
        
        String webpage=adress;
        try{
        in = new URL(webpage).openConnection().getInputStream();
        reader = new InputStreamReader(in);
        } catch (IOException er){
            System.out.println(er);
            
        }
        
        try {
            if(reader != null){
                while(reader.ready()){
                    doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
                    try{
                        kit.read(reader,doc,0);
                    } catch (BadLocationException er){
                        System.out.println(er);
                    }
                }
            }
        } catch(IOException er){
            System.out.println(er);
        }
        HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
            int i = 0;
            while (it.isValid()) {
                SimpleAttributeSet s = (SimpleAttributeSet) it.getAttributes();
                String link = (String) s.getAttribute(HTML.Attribute.HREF);
                if (link != null) {
                    int startOffset = it.getStartOffset();
                    int endOffset = it.getEndOffset();
                    int length = endOffset - startOffset;
                    try {
                    String text = doc.getText(startOffset, length);
                    linkArray[i][0] = text;
                    } catch (BadLocationException er) {
                        System.out.println(er);
                    }
                    linkArray[i][1] = link;
                }  
            i++;
            if(i>49){
            return linkArray;
            }
            it.next();
    }
    return linkArray;
    }
    
}

